package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.Utils.JwtUtils;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtils jwtUtils;

    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody User user) {
        Map<String, Object> response = new HashMap<>();

        try {
            if (userService.existsUsername(user.getUsername())) {
                response.put("success", false);
                response.put("message", "用户名已存在");
                return ResponseEntity.badRequest().body(response);
            }

            userService.save(user);
            response.put("success", true);
            response.put("userId", user.getId()); // 返回新注册用户ID
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "注册失败");
            return ResponseEntity.internalServerError().body(response);
        }
    }
    @GetMapping("/me")
    public Map<String, Object> getCurrentUser(@RequestHeader("Authorization") String token) {
        Map<String, Object> result = new HashMap<>();
        try {
            String cleanToken = token.replace("Bearer ", "");
            result.put("userId", jwtUtils.getUserIdFromToken(cleanToken));
            result.put("username", jwtUtils.getUsernameFromToken(cleanToken));
            result.put("isAdmin", userService.isAdmin(jwtUtils.getUsernameFromToken(cleanToken)));
            return result;
        } catch (Exception e) {
            throw new RuntimeException("无效的Token");
        }
    }
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取完整用户信息
            User authenticatedUser = userService.getUserByCredentials(user.getUsername(), user.getPassword());

            if (authenticatedUser != null) {
                // 生成包含用户ID的JWT
                String token = jwtUtils.generateToken(authenticatedUser.getId(), authenticatedUser.getUsername());

                result.put("success", true);
                result.put("token", token);
                result.put("userId", authenticatedUser.getId());
                result.put("username", authenticatedUser.getUsername());
                result.put("isAdmin", userService.isAdmin(authenticatedUser.getUsername()));
            } else {
                result.put("success", false);
                result.put("message", "用户名或密码错误");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "登录服务异常");
        }
        return result;
    }

    @GetMapping("/validate")
    public boolean validateToken(@RequestHeader("Authorization") String token) {
        return jwtUtils.validateToken(token);
    }

    @GetMapping
    public List<User> getAllUsers(@RequestHeader("Authorization") String token) {
//        if (!jwtUtils.validateToken(token)) {
//            throw new RuntimeException("Invalid token");
//        }
        String username = jwtUtils.getUsernameFromToken(token);
        if (userService.isAdmin(username)) {
            return userService.list();
        }
        User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
        List<User> userList = new ArrayList<>();
        if (user != null) {
            userList.add(user);
        }
        return userList;
    }

    @PostMapping
    public boolean addUser(@RequestBody User user) {
        return userService.save(user);
    }
}